<template>
  <div id="app">
      <header>
          <h1>2024待办事项</h1>
          <form id="new-task-form" @submit.prevent="handleAdd">
              <input
                  type="text"
                  v-model="task"
                  id="new-task-input"
                  placeholder="把计划写下来吧?"
              />
              <input
                  type="submit"
                  id="new-task-submit"
                  placeholder="Add Task"
              />
          </form>
      </header>
      <main>
          <section class="task-list">
              <h2>任务列表</h2>
              <div id="tasks">
                  <template v-for="(item, index) in tasks" :key="index">
                      <div class="task">
                          <div class="content">
                              <input
                                  type="text"
                                  class="text"
                                  v-model="tasks[index]"
                                  :disabled="readonly[index]"
                              />
                          </div>
                          <div class="actions">
                              <button class="edit" @click="handleEdit($event, item, index)">
                                  {{btnName[index]}}
                              </button>
                              <button class="delete" @click="handleDelete(index)">
                                  Delete
                              </button>
                          </div>
                      </div>
                  </template>
              </div>
          </section>
      </main>
  </div>
</template>

<script>
export default {
  data() {
      return {
          tasks: [],
          task: "",
          btnName: [],
          readonly: [],
      };
  },
  methods: {
      handleAdd() {
          if (this.task) {
              this.tasks.push(this.task);
              this.task = "";
              this.btnName.push("编辑");
              this.readonly.push(true);
          }
      },
      handleDelete(index) {
          this.tasks.splice(index, 1);
      },
      handleEdit($event, item, index) {
          console.log($event, item, index);

          if (this.btnName[index] === "编辑") {
              this.btnName[index] = "保存";
              this.readonly[index] = !this.readonly[index];
          } else {
              this.tasks[index] = item;
              this.btnName[index] = "编辑";
              this.readonly[index] = !this.readonly[index];
          }
      },
  },
}
</script>

